package com.zjgsu.nftplatform.service.impl;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.map.MapUtil;
import com.zjgsu.nftplatform.service.NftService;
import com.zjgsu.nftplatform.util.PostUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

/**
 * @author ahy231
 * @date 2022/3/24 21:15
 * @description
 */
@Service
public class NftServiceImpl implements NftService {

    private final RestTemplate restTemplate;
    private final PostUtil postUtil;

    @Value("${myurl.go-server}")
    private String server;

    @Value("${go-server.secret}")
    private String secret;

    public NftServiceImpl(RestTemplate restTemplate, PostUtil postUtil) {
        this.restTemplate = restTemplate;
        this.postUtil = postUtil;
    }

    @Override
    public String getIdByFileHash(String fileHash) {
        byte[] bytes = restTemplate.getForObject("http://" + server + ":8069/nft?method={method}&file_hash={file_hash}&secret={secret}", byte[].class, "getIdByFileHash", fileHash, secret);
        Assert.notNull(bytes, "Failed to get fileId from ipfs server.");
        return new String(bytes, Charset.defaultCharset()).replace("\0", "");
    }

    @Override
    public String getNft(String id) {
        byte[] bytes = restTemplate.getForObject("http://" + server + ":8069/nft?method={method}&id={id}&secret={secret}", byte[].class, "getNft", id, secret);
        Assert.notNull(bytes, "Failed to get nft from ipfs server.");
        return new String(bytes, Charset.defaultCharset()).replace("\0", "");
    }

    @Override
    public String createNft(String fileHash, String address, String password) {
        return postUtil.nftPost(MapUtil.of(
                Pair.of("method", "createNft"),
                Pair.of("file_hash", fileHash),
                Pair.of("address", address),
                Pair.of("password", password)
        ));
    }

    @Override
    public String adapt(String parents, String fileHash, String address, String password) {
        return postUtil.nftPost(MapUtil.of(
                Pair.of("method", "adapt"),
                Pair.of("parents", parents),
                Pair.of("file_hash", fileHash),
                Pair.of("address", address),
                Pair.of("password", password)
        ));
    }
}
